package com.chenye.netty.personalProtocol.server;

import com.chenye.netty.personalProtocol.FunDecoder;
import com.chenye.netty.personalProtocol.FunEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @Auther:chenye
 * @Data:2018/8/16
 * @Description:
 */
public class FunServer {
    public static void main(String[] args){
        EventLoopGroup parent = new NioEventLoopGroup();
        EventLoopGroup children = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parent,children);
            bootstrap.channel(NioServerSocketChannel.class);

            bootstrap.option(ChannelOption.SO_BACKLOG,128);
            bootstrap.option(ChannelOption.SO_KEEPALIVE,true);

            bootstrap.handler(new LoggingHandler());
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    channelPipeline.addLast(new FunEncoder());
                    channelPipeline.addLast(new FunDecoder());
                    channelPipeline.addLast(new FunHandler());
                }
            });
            ChannelFuture future = bootstrap.bind(8080).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            parent.shutdownGracefully();
            children.shutdownGracefully();
        }
    }
}
